package tchk.xyz.lingyuntutorminiprogram.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import tchk.xyz.lingyuntutorminiprogram.dto.UserDTO;
import tchk.xyz.lingyuntutorminiprogram.entity.SysRole;
import tchk.xyz.lingyuntutorminiprogram.entity.SysUser;
import tchk.xyz.lingyuntutorminiprogram.entity.SysUserRole;
import tchk.xyz.lingyuntutorminiprogram.service.ISysRoleService;
import tchk.xyz.lingyuntutorminiprogram.service.ISysUserRoleService;
import tchk.xyz.lingyuntutorminiprogram.service.IUserService;
import tchk.xyz.lingyuntutorminiprogram.utils.Result;

import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/api/admin/user")
@PreAuthorize("hasAuthority('admin:user:manage')")
public class AdminUserController {

    @Autowired
    private IUserService userService;

    @Autowired
    private ISysRoleService roleService;

    @Autowired
    private ISysUserRoleService sysUserRoleService;

    @GetMapping("/list")
    public Result<IPage<UserDTO>> getUserList(@RequestParam(defaultValue = "1") long current,
                                              @RequestParam(defaultValue = "10") long size,
                                              @RequestParam(required = false) String nickname) {
        Page<UserDTO> page = new Page<>(current, size);
        return Result.success(userService.getUserList(page, nickname));
    }

    @PutMapping
    public Result<Void> updateUser(@RequestBody UserDTO userDTO) {
        userService.updateUserWithRoles(userDTO);
        return Result.success();
    }

    /**
     * 获取所有角色的简要列表 (用于前端分配角色的下拉框)
     */
    @GetMapping("/roles")
    public Result<List<SysRole>> getAllRoles() {
        return Result.success(roleService.listAll());
    }

    @GetMapping("/{id}")
    public Result<UserDTO> getUserDetail(@PathVariable Long id) {
        SysUser user = userService.getById(id);
        UserDTO userDTO = new UserDTO();
        BeanUtils.copyProperties(user, userDTO);

        List<SysUserRole> relations = sysUserRoleService.list(new LambdaQueryWrapper<SysUserRole>().eq(SysUserRole::getUserId, id));
        userDTO.setRoleIds(relations.stream().map(SysUserRole::getRoleId).collect(Collectors.toList()));

        return Result.success(userDTO);
    }
}